<?php

class Default_UserController extends Zend_Controller_Action
{

    public function init()
    {
        $option = array(
                'layout'=>'layout',
                'layoutPath'=>APPLICATION_PATH .'/layouts/scripts/default'
        );
        Zend_Layout::startMvc($option);
    }

    public function indexAction()
    {
        // action body
    }

    public function registerAction()
    {
        try{
            if(!Zend_Auth::getInstance()->hasIdentity()){
                $form = new Default_Form_Register();
                $this->view->form = $form;
                $this->view->headTitle('Đăng ký thành viên');
                
//                 $date = new Zend_Date();
//                 $a = date('d-m-Y h:i:s');
//                 echo $date->setTimezone("Asia/Ho_Chi_Minh")->toString("dd-MM-yyyy");
                
                $captcha = $this->generateCaptcha();
                $this->view->captcha = $captcha->render();
                $this->view->captcha_id = $captcha->getId();
                $captcha_session = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captcha->getId());
                $captcha_session->word = $captcha->getWord();
                //remove old captcha
                $this->removeImgCaptcha($captcha->getId());
            
                if($this->_request->isPost()){
                    if($form->isValid($this->_request->getPost())){
                        $model_user = new Application_Model_User();
                        $capt = $form->getValue('txtcaptcha');
                        $capt_id = $this->_request->getParam('cid');
                        $capt_session = new Zend_Session_Namespace('Zend_Form_Captcha_'.$capt_id);
                        
                        
                        $name =$form->getValue('fullname');
                        $gender = $form->getValue('gender');
                        $mail = $form->getValue('email');
                        $password = $form->getValue('password');
                        $repassword = $form->getValue('repassword');
                        $address = $form->getValue('address');
                        $phone = $form->getValue('phone');
                        $date = new Zend_Date();
                        
                        $has_mail = false;
                        foreach ($model_user->fetchAll($model_user->Get_All_User()) as $item_user){
                            if($item_user->user_email == $mail)
                                $has_mail = true;
                        }
                        
                        if($has_mail){
                            $form->email->clearErrorMessages();
                            $form->email->addError('Email này đã được đăng ký, bạn hãy chọn email khác');
                        }
                        else if($password != $repassword){
                            $form->repassword->clearErrorMessages();
                            $form->repassword->addError('Nhắc lại mật khẩu không đúng');
                        }
                        else{
                            if($capt == $capt_session->word){
                                $data = array(
                                        'user_fullname'=>$name,
                                        'password'=>md5($password),
                                        'user_role'=>'member',
                                        'user_address'=>$address,
                                        'user_email'=>$mail,
                                        'user_phone'=>$phone,
                                        'user_gender'=>$gender,
                                        'user_datecreate'=> $date->now('vi_VN')->setTimezone("Asia/Ho_Chi_Minh")->toString("yyyy-MM-dd HH:mm:ss"),     
                                );
                                if($model_user->insert($data)){
                                    $subject = 'Kích hoạt tài khoản LocComputer';
                                    $code = md5($password);
                                    $content = HOST_PATH ."user/active/mail/$mail/code/$code";
                                    $this->Send_Mail($mail, $subject, $content);
                                    $this->_helper->redirector('message', 'user', 'default');
                                }
//                                 echo 'success';
                                
                                
                            }
                            else{
                                $form->txtcaptcha->clearErrorMessages();
                                $form->txtcaptcha->addError('Mã xác nhận không đúng');
                            }
                        }
                    }
                }
                
            }
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
        
    }

    public function gencaptchaAction()
    {
        $captcha = $this->generateCaptcha();
        $this->view->captcha = $captcha->render();
        $this->view->captcha_id = $captcha->getId();
        $captcha_session = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captcha->getId());
        $captcha_session->word = $captcha->getWord();
        $this->_helper->layout()->disableLayout();       
        $this->removeImgCaptcha($captcha->getId());
        
    }

    private function generateCaptcha()
    {
        $captcha = new Zend_Captcha_Image();
        $captcha->setTimeout('300')
                ->setWordlen('4');
        $captcha->setHeight('80')
                ->setWidth('200')
                ->setImgDir(APPLICATION_PATH .'/../public/default/images/captcha/')
                ->setImgUrl($this->view->baseUrl('/default/images/captcha/'))
                ->setFont(APPLICATION_PATH .'/../public/default/images/font/cooprblk.ttf');       
        $captcha->generate();
        return  $captcha;
    }

    private function removeImgCaptcha($imgID)
    {
        $path = APPLICATION_PATH .'/../public/default/images/captcha/';
        $file_list = scandir($path);
        $imgCaptcha = $imgID .'.png';
        foreach ($file_list as $file){
            if($imgCaptcha != $file){
                $file_path = APPLICATION_PATH .'/../public/default/images/captcha/' .$file;
                if(is_file($file_path))
                    unlink($file_path);
            }            
        }
    }

    private function Send_Mail($email, $subject, $content)
    {
        try{
            //create SMTP connection
            $configInfo = array(
                    'auth'=>'login',
                    'username'=>'pham.loc1705@gmail.com',
                    'password'=>'thatwhyyougoaway',
                    'ssl'=>'ssl',
                    'port'=>'465',
            );
            $smtpPort = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $configInfo);
            
            //send mail
            
            $mail = new Zend_Mail('UTF-8');
            $mail->setFrom('pham.loc1705@gmail.com', 'Pham Loc')
                 ->addTo($email)
                 ->setSubject($subject)
                 ->setBodyText($content);
            $mail->send($smtpPort);
            
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
    }

    public function activeAction()
    {
        try{
            $email = $this->_request->getParam('mail');
            $code = $this->_request->getParam('code');
            if($email && $code){
                $model_user = new Application_Model_User();
                $select = $model_user->select()->where('user_email = ?', $email);
                $user = $model_user->fetchRow($select);
                if($user){                    
                    if($user->password == $code){
                        $user->user_actived = 1;
                        $user->save();
                        $this->view->message = 'kích hoạt thành công, bạn có thể đăng nhập vào website với tài khoản đã đăng ký';
                        $this->_helper->layout()->disableLayout();
                    }
                    else
                        $this->view->message = 'kích hoạt tài khoản không thành công, vui lòng kiểm tra lại email đã đăng ký';
                }
            }
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
    }

    public function messageAction()
    {
        $this->view->headTitle('Thông báo');
        
    }

    public function forgetAction()
    {
        try {
            $form = new Default_Form_Forget();
            $this->view->form = $form;
            $new_pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
            $this->view->headTitle('Cấp lại mật khẩu');
            
            if($this->_request->isPost()){
                if($form->isValid($this->_request->getPost())){
                    $model_user = new Application_Model_User();
                    $email = $form->getValue("email");
                    $select = $model_user->select()->where("user_email = ?", $email);
                    $row = $model_user->fetchRow($select);
                    if($row){
                        $subject = 'Mật khẩu mới';
                        $content  = 'Mật khẩu mới của bạn là: ' .$new_pass;
                        $this->Send_Mail($email, $subject, $content);
                        
                        $row->password = md5($new_pass);
                        $row->save();
                    }
                    else {
                        $form->email->clearErrorMessages();
                        $form->email->addError("Không tìm thấy Email bạn yêu cầu");
                    }
                }
            }
        }
        catch (Zend_Exception $ex){
            
        }
    }

    public function editinfoAction()
    {
        try {
            $auth = Zend_Auth::getInstance();
            if(($auth->hasIdentity()) && ($auth->getIdentity()->user_role == 'member')){
                
                $form = new Default_Form_Edituser();
                $model_user = new Application_Model_User();
                $this->view->form = $form;
                $id = $this->_request->getParam('id');
                if($id){
                    $row_user = $model_user->find($id)->current();
                    if($row_user){
                        $form->populate($row_user->toArray());//populate data to form
                        $this->view->img = $row_user->user_image;
                        
                        if($this->_request->isPost()){
                            if($form->isValid($this->_request->getPost())){
                                $row_user->user_fullname = $form->getValue('user_fullname');
                                $row_user->user_address = $form->getValue('user_address');
                                $row_user->user_phone = $form->getValue('user_phone');
                                $row_user->user_image = $form->getValue('user_image');
                                $row_user->user_gender = $form->getValue('user_gender');
                                if($form->user_image->isUploaded){
                                    $form->user_image->receive();
                                }
                                $row_user->save();
                                $this->redirect(array('module'=>'default', 'controller'=>'index', 'action'=>'index'));
                            }
                        }
                    }
                }
            }
            else{
                $this->redirect(array('module'=>'default', 'controller'=>'index', 'action'=>'index'));
            }
            
            
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
    }

    public function changepassAction()
    {
        try{
            $auth = Zend_Auth::getInstance();
            if($auth->hasIdentity() && $auth->getIdentity()->user_role == "member"){
                $id_user = $auth->getIdentity()->user_id;
                $model_user = new Application_Model_User();
                $row = $model_user->find($id_user)->current();
                if($row){
                    $this->view->headTitle("Thay đổi mật khẩu");
                    $form = new Default_Form_Changepass();
                    $this->view->form = $form;
                   
                    
                    if($this->_request->isPost()){
                        if($form->isValid($this->_request->getPost())){
                            $old_pass = $form->getValue("oldpass");
                            $new_pass = $form->getValue("newpass");
                            $re_pass = $form->getValue("renewpass");
                            if($row->password == md5($old_pass)){
                                if($new_pass == $re_pass){
                                    $row->password = md5($new_pass);
                                    $row->save();
                                }
                                else {
                                    $form->renewpass->clearErrorMessages();
                                    $form->renewpass->addError("Mật khẩu nhập lại không đúng");
                                }
                            }
                            else{
                                $form->oldpass->clearErrorMessages();
                                $form->oldpass->addError("Không khớp với mật khẩu cũ");
                            }
                        }
                    }
                }
                
                
            }
            else $this->redirect(array('module'=>'default', 'controller'=>'index', 'action'=>'index'));
        }
        catch (Zend_Exception $ex){
            
        }
    }


}















